package com.xinkao.log.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.context.annotation.Profile;
import org.springframework.core.io.ClassPathResource;

import java.io.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * @author 周洋
 * @Description json字符串中key值下划线命名转换为驼峰命名
 * @createTime 2021/4/22 9:19
 */
public class JsonUtils {

    public final static void convert(Object json) {
        if (json instanceof JSONArray) {
            JSONArray arr = (JSONArray) json;
            for (Object obj : arr) {
                convert(obj);
            }
        } else if (json instanceof JSONObject) {
            JSONObject jo = (JSONObject) json;
            Set<String> keys = jo.keySet();
            String[] array = keys.toArray(new String[keys.size()]);
            for (String key : array) {
                Object value = jo.get(key);
                String[] key_strs = key.split("_");
                if (key_strs.length > 1) {
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < key_strs.length; i++) {
                        String ks = key_strs[i];
                        if (!"".equals(ks)) {
                            if (i == 0) {
                                sb.append(ks);
                            } else {
                                int c = ks.charAt(0);
                                if (c >= 97 && c <= 122) {
                                    int v = c - 32;
                                    sb.append((char) v);
                                    if (ks.length() > 1) {
                                        sb.append(ks.substring(1));
                                    }
                                } else {
                                    sb.append(ks);
                                }
                            }
                        }
                    }
                    jo.remove(key);
                    jo.put(sb.toString(), value);
                }
                convert(value);
            }
        }
    }

    public final static void convert(List<JSONObject> jsonObjectList) {
        for (JSONObject jo:jsonObjectList) {
            Set<String> keys = jo.keySet();
            String[] array = keys.toArray(new String[keys.size()]);
            for (String key : array) {
                Object value = jo.get(key);
                String[] key_strs = key.split("_");
                if (key_strs.length > 1) {
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < key_strs.length; i++) {
                        String ks = key_strs[i];
                        if (!"".equals(ks)) {
                            if (i == 0) {
                                sb.append(ks);
                            } else {
                                int c = ks.charAt(0);
                                if (c >= 97 && c <= 122) {
                                    int v = c - 32;
                                    sb.append((char) v);
                                    if (ks.length() > 1) {
                                        sb.append(ks.substring(1));
                                    }
                                } else {
                                    sb.append(ks);
                                }
                            }
                        }
                    }
                    jo.remove(key);
                    jo.put(sb.toString(), value);
                }
                convert(value);
            }
        }

    }

    public final static Object convert(String json) {
        Object obj = JSON.parse(json);
        convert(obj);
        return obj;
    }

    /**
     * json去掉空格
     * @param jsonObject
     * @return
     */
    public static JSONObject jsonStrTrim(JSONObject jsonObject){

        if( jsonObject != null){
            Iterator itt = jsonObject.keySet().iterator();
            while (itt.hasNext()) {
                String key = itt.next().toString();
                String value = jsonObject.getString(key);

                if(value == null){
                    continue ;
                }else if("".equals(value.trim())){
                    continue ;
                }else{
                    jsonObject.put(key, value.trim());
                }
            }
        }
        return jsonObject;
    }

    public static String readJSON(String fileName) throws Exception {

        ClassPathResource classPathResource = new ClassPathResource("json/"+fileName);
        BufferedReader reader = new BufferedReader(new InputStreamReader(classPathResource.getInputStream()));

        StringBuilder sb = new StringBuilder();
        String line = "";
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        String result = sb.toString().replaceAll("\r\n", "");

        return result;
    }

    public static void updateJSON(String fileName, HashMap<String, String> map) throws Exception {

        JSONObject jsonObject = JSON.parseObject(readJSON(fileName));
        JSONArray links = jsonObject.getJSONArray("links");

        for (int i = 0; i < links.size(); i++) {
            JSONObject item1 = links.getJSONObject(i);
            if (item1.getString("name").equalsIgnoreCase(map.get("name"))) {
                item1.put("content", map.get("content"));
            }
        }

        JSONObject nItem = new JSONObject();
        nItem.put("links", links);
        String nContent = JSON.toJSONString(nItem);

        String filePath = Profile.class.getClassLoader().getResource(fileName).toURI().getPath();

        BufferedWriter bw = null;
        try {
            bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath)));
            bw.write("");
            bw.write(nContent);
            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}